﻿// body onload event 에서 호출함
//document.documentElement.style.display = "none";
function InitPage()
{
  setButtonAuth();
  //document.body.oncontextmenu = function () { return false; };

  //var startTime = new Date().getTime();
  LoadPage();
  ____pageLoaded = true;
  //alert(new Date().getTime() - startTime);
  //document.documentElement.style.display = "";
}
/*
function findFrameByName(frameName, direction, firstFrame)
{
  firstFrame = firstFrame || window;
  direction = direction || 'UP';
  if ( direction == 'UP' )
  {
    for ( var frame = firstFrame; ; frame = frame.parent)
    {
      if ( frame.name == frameName )
        return frame;
      if ( frame == top )
        break;
    }
  }
  else
  {
    var frame = firstFrame;
    if ( frame.name == frameName )
      return frame;
    for ( var n = 0, nlen = frame.frames.length; n < nlen; n++ )
    {
      var frame = findFrameByName(frameName, direction, frame.frames[n]);
      if ( frame )
        return frame;
    }
  }
  return null;

}
ehrTopFrame = findFrameByName('ehrTopFrame') || top;
*/
// trim string
function trim(str) {
  if ( str == null || typeof str != "string" ) return str;
  return str.replace(/^\s*|\s*$/g, ""); // 문장의 앞과 뒤의 공백 제거
}

// get bytes length
function getByteLength(s)
{
  var blen = 0, charCode;
  for ( var n = 0; n < s.length; n++ )
  {
    charCode = s.charCodeAt(n);
    blen += charCode > 0xffffff ? 4 : charCode > 0xffff ? 3 : charCode > 0xff ? 2 : 1;
  }
  return blen;
}

// ibsheet savename 을 | 로 묶는다.
function concatSaveName(sheet, delim, exceptSaveNames)
{
  var exceptSaveNameArr = exceptSaveNames ? exceptSaveNames.split(",") : [];
  if ( delim == null ) delim = "|";
  var savename;
  var savenames = "";
  for ( var n = 0; n <= sheet.LastCol; n++ )
  {
    savename = sheet.ReadDataProperty(0, n, dpSaveName);
    if ( savename.substr(0, 7) != "COLHEAD" )
    {
      savenames += (isinarr(savename, exceptSaveNameArr) ? " " : savename) + delim;
    }
  }
  return savenames;
}

// str 을 cnt 만큼 반복한다.
function repeatStr(str, cnt)
{
  var rslt = "";
  for ( var n = 0; n < cnt; n++ )
  {
    rslt += str;
  }
  return rslt;
}

// sheet 에서 체크된 row 데이타를 구성하여 배열로 만들어 return 한다. grid 를 구성한다.
function sheet_getData(sheet, chkSvnm)
{
  var grid = {};

  // set column name
  var arrColName = [];
  var mapColName = {};
  for ( var col = 0; col <= sheet.LastCol; col++ )
  {
    arrColName[arrColName.length] = sheet.ColSaveName(col);
    mapColName[sheet.ColSaveName(col)] = col;
  }
  grid.arrColName = arrColName;
  grid.mapColName = mapColName;

  // set data
  var arrData = [];
  for ( var row = sheet.HeaderRows, rcnt = 0; rcnt < sheet.RowCount; row++, rcnt++ )
  {
    if ( chkSvnm == null || (typeof(chkSvnm) == "function" && chkSvnm(sheet, row)) || sheet.CellValue(row, chkSvnm) == "1" )
    {
      var colData = [];
      for ( var col = 0; col <= sheet.LastCol; col++ )
      {
        colData[colData.length] = sheet.CellValue(row, col);
      }
      arrData[arrData.length] = colData;
    }
  }
  grid.arrData = arrData;
  // set interface
  grid.RowCount = arrData.length;
  grid.ColCount = grid.arrColName.length;

  return grid;
}

// grid 의 cell value 를 가져한다.
function grid_CellValue(grid, row, colNm)
{
  var col = ( typeof colNm == "number" ) ? colNm : array_indexOf(grid.arrColName, colNm);
  //var col = ( typeof colNm == "number" ) ? colNm : grid.mapColName[colNm];
  return grid.arrData[row][col];
}

// grid 의 column name 을 가져한다.
function grid_ColName(grid, col)
{
  return grid.arrColName[col];
}

// 배열에서 val 에 해당하는 index 를 찾는다.
function array_indexOf(array, val)
{
  for ( var n = 0; n < array.length; n++ )
  {
    if ( array[n] == val )
    {
      return n;
    }
  }
  return -1;
}
// 폼데이타를 key 형식으로 구성하여 return
function form_getData(form)
{
  var element;
  var elearray;
  var formdata = {};

  for ( var n = 0; n < form.elements.length; n++ )
  {
    element = form.elements[n];
    if ( element.name )
    {
      elearray = formdata[element.name] == null ? formdata[element.name] = new Array : formdata[element.name];

      switch ( element.tagName )
      {
        case "SELECT":
        {
          if ( element.multiple )
          {
            for ( var m = 0; m < element.options.length; m++ )
            {
              if ( element.options[m].selected )
              {
                elearray[elearray.length] = element.value;
              }
            }
          }
          else
          {
            elearray[elearray.length] = element.value;
          }
        }
        break;
        case "INPUT":
        {
          switch ( element.type )
          {
            case "checkbox":
            case "radio":
            {
              if ( element.checked )
              {
                elearray[elearray.length] = element.value;
              }
            }
            break;
            default:
            {
              elearray[elearray.length] = element.value;
            }
            break;
          }
          break;
        }
        break;
        default:
        {
          elearray[elearray.length] = element.value;
        }
        break;
      }
    }
  }

  return formdata;
}
// radio 버튼 중 check 된 값을 return;
function getCheckedValue(radio) {
  var size = radio.length;
  if ( ! size ) {
    return radio.checked ? radio.value : null;
  }
  for ( var n = 0; n < size; n++ ) {
    if ( radio[n].checked ) {
      return radio[n].value;
    }
  }
  return null;
}

// val 에 해당하는 라디오 버튼을 check 한다.
function checkRadio(radio, val, bClick)
{
  var len = radio.length;
  if ( len )
  {
    for ( var n = 0; n < len; n++ )
    {
      if ( radio[n].value == val )
      {
        radio[n].checked = true;
        if ( bClick ) radio[n].onclick();
        return n;
      }
      else
      {
        radio[n].checked = false;
      }
    }
  }
  else
  {
    if ( radio.value == val )
    {
      radio.checked = true;
      if ( bClick ) radio.onclick();
      return 0;
    }
    else
    {
      radio.checked = false;
    }
  }
  return -1;
}

// 라디오 버튼을 모두 uncheck 한다.
function uncheckRadioAll(radio)
{
  var len = radio.length;
  if ( len )
  {
    for ( var n = 0; n < len; n++ )
    {
      radio[n].checked = false;
    }
  }
  else
  {
    radio.checked = false;
  }
}

// 버튼이나 폼엘리먼트를 활성 비활성화 한다.
function enableInput(input, b, convertCombo)
{
  b = b ? true : false;
  if ( input == null ) alert("enableInput: input is null !!!");

  if (typeof input == 'string')
    input = document.getElementById(input);

  switch (input.tagName)
  {
    case "INPUT":
    {
      switch ( input.type )
      {
        //case "hidden":
        case "text":
        case "password":
        {
          input.readOnly = (!b);
          input.style.backgroundColor = b ? "":"#eeeeee";
        }
        break;
        case "image":
        case "button":
        {
          input.disabled = (!b);
          input.style.filter = b ? "":"gray";
          input.style.cursor = b ? "hand":"arrow";
        }
        break;
        case "checkbox":
        case "radio":
        case "file":
        case "reset":
        case "submit":
        {
          input.disabled = (!b);
        }
        break;
      }
    }
    break;
    case "SELECT":
    {
      input.disabled = (!b);
      if ( convertCombo == true) convertCombo2Text(input, !!b);
    }
    break;
    case "TEXTAREA":
    {
      input.readOnly = (!b);
      input.style.backgroundColor = b ? "":"#eeeeee";
    }
    break;
    case "IMG":
    {
      input.disabled = (!b);
      input.style.filter = b ? "":"gray";
      input.style.cursor = b ? "hand":"arrow";
    }
    break;
  }
}

function enableInputButtonAll(tf)
{
  $A(document.getElementsByTagName("INPUT")).select(function (e)
  {
    return e.type == "button";
  }).each(function(e)
  {
    enableInput(e, tf);
  });
}

// string 이 null 일 경우 빈 문자열을 리턴한다.
function null2empty(s)
{
  return s == null ? "" : s;
}

// string 이 null 또는 빈문자열일 경우 디폴트 문자열을 리턴한다.
function nvl(s, d)
{
  return s == null || s == "" ? (d == null ? "" : d) : s;
}

// YMD 형식의 날짜를 포맷 형식으로 포매팅한다. 디폴트 포맷은 y.m.d
function ymd2fmt(ymd, fmt)
{
  var y = ymd.substr(0, 4);
  var m = ymd.substr(4, 2);
  var d = ymd.substr(6, 2);
  if ( fmt == null ) fmt = "y-m-d";
  var result = "";
  for ( var n = 0; n < fmt.length; n++ )
  {
    switch ( fmt.charAt(n) )
    {
      case "y":
      {
        result += y;
      }
      break;
      case "m":
      {
        result += m;
      }
      break;
      case "d":
      {
        result += d;
      }
      break;
      default:
      {
        result += fmt.charAt(n);
      }
      break;
    }
  }
  return result;
}

function ymd2date(ymd)
{
  return new Date(
    Number(ymd.substr(0, 4)),
    Number(ymd.substr(4, 2))-1,
    Number(ymd.substr(6, 2)));
}
// 콤보박스를 선택한다.
function setSelect(sel, v)
{
  for ( var n = 0; n < sel.options.length; n++ )
  {
    if ( v == sel.options[n].value )
    {
      sel.options[n].selected = true;
      return true;
    }
  }

  return false;
}

// id 로 HTML 객체를 가져온다.
function tid(id)
{
  return document.getElementById(id);
}
/*
// 모달팝업을 띄운다. 사용금지 대신에 popmodal2
function popmodal(url, args, resizable)
{
  if ( args == null ) args = {};
  return showModalDialog(url, args, "help:no; status:no; resizable:"+(resizable?"yes":"no")+"; ");
}
*/

// frameName 에 해당하는 프레임이 존재하는지 check
function checkExistsFrameByName(frameName, win)
{
  win = win || window.parent;

  // alert( win.frames.length );
  for ( var n = 0, nlen = win.frames.length; n < nlen; n++ )
  {
	try
	{
		// alert( win.frames(n).name );
		if ( win.frames[n].name == frameName )
		  return true;
		if ( checkExistsFrameByName(frameName, win.frames[n]) )
		  return true;
	} catch (e) { }

  }
  return false;
}

// 모달팝업의 사이즈를 변경한다.
function sizeDialog(w, h)
{
  document.documentElement.style.display = "none";
  parent.dialogWidth = w + "px";
  parent.dialogHeight = (h+55) + "px";// for ie7.0

  parent.dialogTop = (window.screen.height - Number(parent.dialogHeight.replace(/\D/g, "")))/2;
  parent.dialogLeft = (window.screen.width - Number(parent.dialogWidth.replace(/\D/g, "")))/2;
  document.documentElement.style.display = "";
}

// 윈도우팝업의 사이즈를 변경한다.
function sizeWindow(w, h)
{
  parent.resizeTo(w, h);
  var wtop = (window.screen.height - h)/2;
  var wleft = (window.screen.width - w)/2;
  parent.moveTo(wleft, wtop);
}

// 값이 포함되는지 검사한다.
function isin(o)
{
  for ( var n = 1; n < arguments.length; n++ )
  {
    if ( o == arguments[n] )
    {
      return true;
    }
  }
  return false;
}

// 값이 배열에 포함되는지 검사한다.
function isinarr(o, arr)
{
  for ( var n = 0; n < arr.length; n++ )
  {
    if ( o == arr[n] )
    {
      return true;
    }
  }
  return false;
}

// 값이 구간에 포함되는지 검사한다.
function between(o, from, to)
{
  return o >= from && o <= to;
}

// url 을 호출하여 응답을 가져온다.
function openHttpRequest(url, returnType)
{
  // returnType 0:text, 1:xdom
  if ( returnType == null )
  {
    returnType = 0;
  }

  var xmlhttp = null;
  if ( window.XMLHttpRequest )
  {
    xmlhttp = new XMLHttpRequest();
  }
  else if ( window.ActiveXObject )
  {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");//MSXML2.XMLHTTP
  }
  else
  {
    alert("Can not create HttpRequest !!!");
    return null;
  }
  //var xmlhttp = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");

  xmlhttp.open("GET", url, false);
  xmlhttp.send();

  if ( xmlhttp.status != 200 )
  {
    alert(xmlhttp.statusText);
    return null;
  }

  if ( returnType == 0 ) return xmlhttp.responseText;

  //alert(xmlhttp.responseText);

  //return xmlhttp.responseXML;

  return makeXSheetWithXmlText(xmlhttp.responseText, returnType);

}

function makeXSheetWithXmlText(xmlText, mode)
{
  xmlText = trim(xmlText);
  mode = nvl(mode, "xml");
  if ( mode == "xml")
  {
    var xdom = Try.these(
      function() {return new ActiveXObject("Microsoft.XMLDOM")},
      //function() {return new ActiveXObject('Msxml2.DOMDocument50')},
      function() {return new ActiveXObject("Msxml2.DOMDocument")}
    );

    if ( xdom == null )
    {
      alert("XML Parser 생성에 실패하였습니다.");
      return null;
    }

    xdom.async = false;
    xdom.loadXML(xmlText);

    if ( xdom.parseError.errorCode != 0 )
    {
      var parseErrMsg = "";
      parseErrMsg += "ErrorCode: "+xdom.parseError.errorCode+"\n";
      parseErrMsg += "Reason: "+xdom.parseError.reason+"\n";
      parseErrMsg += "Line: "+xdom.parseError.line+"\n";
      alert("Xml Parsing 오류가 발생하였습니다.\n\n"+parseErrMsg);
      return null;
    }

    var xsheet = new XmlSheet(xdom);
    var msg = xsheet.getMessage();
    if ( msg )
    {
      if ( doCheckMsg(msg) )
      {
        alert("작업 중 오류가 발생하였습니다.\n\n"+msg);
      }
      return null;
    }

    xsheet.responseText = xmlText;
    return xsheet;
  }
  else if ( mode == "script" )
  {
    var so;
    try
    {
      eval("so = "+xmlText);
    }
    catch(e)
    {
      alert("script error: "+e);
      return null;
    }
    var x = new ScriptSheet(so);
    var msg = x.getMessage();
    if ( msg )
    {
      if ( doCheckMsg(msg) )
      {
        alert("작업 중 오류가 발생하였습니다.\n\n"+msg);
      }
      return null;
    }

    x.responseText = xmlText;
    return x;

  }
}

if ( window.Class )
{
  // XSheet 객체
  var XmlSheet = Class.create();
  Object.extend(XmlSheet.prototype, {
    initialize: function(xdom)
    {
      this.xdom = xdom;
      this.data_key = "default";
      this.currRowIdx = -1;
      this.meta = {};
      this.createMetaData();
    },
    createMetaData: function()
    {
      var dataNodes = this.xdom.selectNodes("/SHEET/DATA");
      var ColNameMap, NameColMap, columnName, filter, data_key, trNodes;
      for ( var n = 0, nlen = dataNodes.length; n < nlen; n++ )
      {
        data_key = dataNodes[n].selectSingleNode("@KEY").text;
        filter = "@KEY='"+data_key+"'", ColNameMap = {}, NameColMap = {};

        var htrNode = dataNodes[n].selectSingleNode("HTR");
        for ( var c = 0, clen = htrNode.childNodes.length; c < clen; c++ )
        {
          columnName = htrNode.childNodes[c].text;

          ColNameMap[c] = columnName;
          NameColMap[columnName] = c;
        }

        trNodes = dataNodes[n].selectNodes("TR");

        this.meta[data_key] = {
          RowCount: trNodes.length,
          ColumnCount: htrNode.childNodes.length,
          ColNameMap: ColNameMap,
          NameColMap: NameColMap,
          trNodes: trNodes
        };
      }
    },
    next: function(data_key)
    {
      var next = this.RowCount(data_key) > this.currRowIdx + 1;
      if ( next ) this.currRowIdx++;
      return next;
    },
    setDataKey: function(data_key)
    {
      data_key = nvl(data_key, "default");
      this.data_key = data_key;
    },
    EtcData: function(key)
    {
      try
      {
        return this.xdom.selectSingleNode("/SHEET/ETC-DATA/ETC[@KEY='"+key+"']").text;
      }
      catch(e)
      {
        return "";
        /*
        alert("Error at xsheet.EtcData !!!");
        throw e;
        */
      }
    },
    getMessage: function()
    {
      return this.xdom.selectSingleNode("/SHEET/MESSAGE").text;
    },
    RowCount: function(data_key)
    {
      return this.meta[data_key || this.data_key].RowCount;
    },
    ColCount: function(data_key)
    {
      return this.meta[data_key || this.data_key].ColumnCount;
    },
    ColName: function(col, data_key)
    {
      return this.meta[data_key || this.data_key].ColNameMap[col];
    },
    CellIndex: function(colnm, data_key)
    {
      return this.meta[data_key || this.data_key].NameColMap[colnm];
    },
    CellValue: function(row, col, data_key)
    {
      try
      {
        row = (row == null ? this.currRowIdx : row);
        var colNum = col.constructor == Number ? col : this.meta[data_key || this.data_key].NameColMap[col];
        return this.meta[data_key || this.data_key].trNodes[row].selectSingleNode("TD["+colNum+"]").text;
      }
      catch (e)
      {
        alert("Error at xs.CellValue("+[row, col, data_key]+") !!!");
        throw e;
      }
    },
    exists: function(data_key)
    {
      return this.meta[data_key || this.data_key] != null;
    },
    FindRow: function(col, val, row, data_key)
    {
      var xs = this;
      for ( var r = nvl(row, 0), rcnt = xs.RowCount(data_key); r < rcnt; r++ )
      {
        if ( xs.CellValue(r, col, data_key) == val ) return r;
      }
      return -1;
    },
    FindRows: function(col, val, row, data_key)
    {
      var xs = this;
      var result = [];
      var index = 0;
      for ( var r = nvl(row, 0), rcnt = xs.RowCount(data_key); r < rcnt; r++ )
      {
        if ( xs.CellValue(r, col, data_key) == val ) {
        	result[ index++ ] = r;
        }
      }
      return result;
    },
    FindRowWithFunction: function(fFind, reverse, startRow, data_key)
    {
      var findRow = -1;
      this.eachRow(function(row, xs, returnObject)
      {
        if ( fFind(xs, row) )
        {
          findRow = row;
          throw $break;
        }
      }, reverse, startRow, data_key);
      return findRow;
    },
    eachRow: function(f, reverse, startRow, data_key)
    {
      var xs = this;
      reverse = !!reverse;
      var returnObject = {};
      try
      {
        if ( reverse )
          for ( var row = nvl(startRow, xs.RowCount(data_key)-1), firstDataRow = 0; row >= firstDataRow; row-- )
            f(row, xs, returnObject);
        else
          for ( var row = nvl(startRow, 0), RowCount = xs.RowCount(data_key); row < RowCount; row++)
            f(row, xs, returnObject);
      }
      catch(e)
      {
        if (e == $break) return returnObject.value;
        else throw e;
      }

    }
  });

  // ScriptSheet 객체
  var ScriptSheet = Class.create();
  Object.extend(ScriptSheet.prototype, XmlSheet.prototype);
  Object.extend(ScriptSheet.prototype, {
    initialize: function(so)
    {
      this.so = so;
      this.etcData = so.etcData;
      this.listData = so.listData;
      this.message = so.message;
      this.data_key = "default";
      this.currRowIdx = -1;
      this.meta = {};
      this.createMetaData();
    },
    createMetaData: function()
    {
      var ColNameMap, NameColMap, columnName;
      for ( var data_key in this.listData)
      {
        ColumnCount = this.listData[data_key].columnNames.length;
        ColNameMap = {}, NameColMap = {};

        for ( var c = 0, clen = ColumnCount; c < clen; c++ )
        {
          columnName = this.listData[data_key].columnNames[c];

          ColNameMap[c] = columnName;
          NameColMap[columnName] = c;
        }

        this.meta[data_key] = {
          RowCount: this.listData[data_key].data.length,
          ColumnCount: ColumnCount,
          ColNameMap: ColNameMap,
          NameColMap: NameColMap
        };

      }

    },
    EtcData: function(key)
    {
      return nvl(this.etcData[key]);
    },
    getMessage: function()
    {
      return this.message;
    },
    CellValue: function(row, col, data_key)
    {
      try
      {
        row = (row == null ? this.currRowIdx : row);
        var colNum = col.constructor == Number ? col : this.meta[data_key || this.data_key].NameColMap[col];
        return this.listData[data_key || this.data_key].data[row][colNum];
      }
      catch (e)
      {
        alert("Error at xs.CellValue("+[row, col, data_key]+") !!!");
        throw e;
      }
    }
  });

}

// ie patch 로 인한 object 비활성화 해결
function docwrite(s)
{
  document.write(s);
}

// xsheet 를 이용하여 select box 구성한다.
function makeSelectXS(sel, xsheet, data_key)
{
  if ( xsheet == null ) return;

  for ( var row = 0, rcnt = xsheet.RowCount(data_key); row < rcnt; row++ )
  {
    sel.options.add(new Option(xsheet.CellValue(row, 0, data_key), xsheet.CellValue(row, 1, data_key)));
  }
}

// xsheet 에서 특정 컬럼의 값을 배열로 리턴한다.
function getCellValuesXS(xsheet, col, data_key)
{
  var arr = [];
  for ( var row = 0, rcnt = xsheet.RowCount(data_key); row < rcnt; row++ )
  {
    arr[arr.length] = xsheet.CellValue(row, col, data_key);
  }
  return arr;
}

// make sheet combo value
function makeSCV(xsheet, data_key)
{
  return xsheet ? getCellValuesXS(xsheet, 1, data_key).join("|") : "";
}

// make sheet combo text
function makeSCT(xsheet, data_key)
{
  return xsheet ? getCellValuesXS(xsheet, 0, data_key).join("|") : "";
}

function sheetSpeedDown2Excel(sheet)
{
  sheet.SpeedDown2Excel(-1, false, false, "", "/common/jsp/ibsheet_excel_design.jsp?S_HEADER_ROWS="+sheet1.HeaderRows, false, true, "", false);
}

// write ibchart
function writeIBChart(obj)
{
  obj = Object.extend({classid: "clsid:9cd77d36-9a9f-4cf8-86c5-18ae5b8ca118", codebase: "/resource/file/ibchart.cab#version=1,0,0,13"}, obj);
  //writeObjectTag(obj);

  var html = "";
  html += "<object id='"+ obj.id +"' \n";
  html += "  classid='"+ obj.classid +"' \n";
  html += "  codebase='"+ obj.codebase +"' width='"+nvl(obj.width, "100%")+"' height='"+nvl(obj.height, "100%")+"' style=margin:0; >\n";
  html += "</object>\n";
  document.write(html);

}

// class, method 로 xsheet 객체를 가져온다.
function getXSheet(S_DSCLASS, S_DSMETHOD, params)
{
  var param = "";
  param += "&S_FORWARD=xsheetResultXML";
  param += "&S_DSCLASS="+S_DSCLASS;
  param += "&S_DSMETHOD="+S_DSMETHOD;
  param += nvl(params, "");
  return openHttpRequest("/commonAction.do?x=x"+param, 2);
}



// 시트 메시지를 체크한다. 주로 로그인여부를 체크할 예정.
function doCheckMsg(msg)
{
  msg = nvl(msg);
  if ( msg.startsWith("LOGIN_CHECK_FAIL") )
  {
    if ( confirm(msg.substr("LOGIN_CHECK_FAIL".length+1)+"\n\n다시 로그인 하시겠습니까?") )
    {
      checkLogout();
    }
    return false;
  }
  else return true;
}

// 공통 시트 행추가, 회사에 맞게 마지막행, 현재행, 첫행에 추가
function sheetDataInsert(sheet)
{
  return sheet.DataInsert(-1);
}

// 첫번째 text box 에 focus 한다.
function focusFirstTextBox()
{
  var elements = document.getElementsByTagName("INPUT");
  for ( var n = 0; n < elements.length; n++ )
  {
    try
    {
      if ( elements[n].type == "text" && elements[n].style.display != "none" && elements[n].style.imeMode == "")
      {
        try { elements[n].focus(); } catch(ex) {}
        break;
      }
    }
    catch(e)
    {
    }
  }
}

// 엔터가 눌려졌는지 검사한다.
function enterKeyDown()
{
  return event.keyCode == 13;
}

// xsheet 를 이용하여 시트콤보 또는 콤보박스를 구성한다.
function makeComboXS(xsheet, data_key, obj, saveName, optionASN, arrPair, sheetRow)
{
  if ( xsheet == null ) return;

  if ( obj.tagName == "OBJECT" )
  {
    var textH = "";
    var valueH = "";
    switch ( optionASN )
    {
      case "A":
      {
        textH = "전체|";
        valueH = "%|";
      }
      break;
      case "S":
      {
        textH = "선택|";
        valueH = " |";
      }
      break;
      case "N":
      {
        textH = "| |";
        valueH = "||";
      }
      break;
      case "U":
      {
        var arrText = [];
        var arrVal = [];
        for ( var n = 0; n < arrPair.length; n++ )
        {
          arrText[arrText.length] = arrPair[n][0];
          arrVal[arrVal.length] = arrPair[n][1];
        }
        textH = arrPair.length == 0 ? "" : arrText.join("|")+"|";
        valueH = arrPair.length == 0 ? "" : arrVal.join("|")+"|";
      }
      break;
    }
    if ( sheetRow == null )
    {
      obj.InitDataCombo(0, saveName, textH + makeSCT(xsheet, data_key), valueH + makeSCV(xsheet, data_key), "", "");
    }
    else
    {
      obj.CellComboItem(sheetRow, saveName, textH + makeSCT(xsheet, data_key), valueH + makeSCV(xsheet, data_key));
    }
  }
  else if ( obj.tagName == "SELECT" )
  {
    switch ( optionASN )
    {
      case "A":
      {
        obj.options.add(new Option("-전체-", ""));
      }
      break;
      case "S":
      {
        obj.options.add(new Option("-선택-", ""));
      }
      break;
      case "N":
      {
        obj.options.add(new Option("", ""));
      }
      break;
    }

    makeSelectXS(obj, xsheet, data_key);
  }
}

function makeComboTextXS(xs, data_key, delCol, delRow)
{
  delCol = delCol || "□";
  delRow = delRow || "■";
  var tmpArr = [];
  for ( var r = 0, RowCount = xs.RowCount(data_key); r < RowCount; r++ )
  {
    tmpArr.push([xs.CellValue(r, 0, data_key), xs.CellValue(r, 1, data_key)]);
  }

//alert(tmpArr);
  var comboText = tmpArr.inject([], function(result, v)
  {
    result.push(v.join(delCol));
    return result;
  }).join(delRow);
  //alert(comboText);
  return comboText;

}

// write ibsheet
function writeIBSheet(skin_path, id, width, height, classid, codebase, ConfigXml, Visible)
{
  var id = nvl(id, "sheet1");
  //var classid = nvl(classid, "CLSID:C838E9DA-1625-4E14-8B37-C6706B43C423");
  //var codebase = nvl(codebase, "/resource/file/IBSheet.CAB#version=2,6,0,0");
  var classid = nvl(classid, "CLSID:341FBC5F-2AE4-41B8-BFE5-A03170569A27");
  var codebase = nvl(codebase, "/resource/file/IBSheet3.CAB#version=3,4,0,50");

  var ConfigXml = nvl(ConfigXml, skin_path+"/style/IBSheet_design.xml");
/*
  if ( location.hostname == "172.16.2.19" )
  {
    ConfigXml = location.protocol +"//"+ location.hostname + ":8088"+ConfigXml;
  }
*/
//alert(ConfigXml);
  var Visible = nvl(Visible, "false");
  var html = "";
  html += "<object id='"+ id +"' \n";
  html += "  classid='"+ classid +"' \n";
  html += "  codebase='"+ codebase +"' width='"+nvl(width, "100%")+"' height='"+nvl(height, "100%")+"' style=margin:0; >\n";
  html += "  <param name=ConfigXml value='"+ ConfigXml +"' >\n";
  html += "  <param name=Visible value='"+ Visible +"' >\n";
  html += "  <param name=AutoSizeMode value='true' >\n";
  html += "</object>\n";
  document.write(html);
}


// 시트 정의를 손쉽게
function InitSheetColumn(sheet, arrC, header0)
{
  //sheet.ConfigXml = Page.SKIN_PATH+"/style/IBSheet_design.xml";
/*
  with ( sheet )
  {
    MessageText("ConfirmTitle") = "Confirm";
    MessageText("WarningTitle") = "Warning";
    MessageText("WarningImage") = "!";
    MessageText("MessageShowLevel") = "UEDX";
    DateFormatChar = "-";
    HeadBackColor = RgbColor(102,153,204);
    DataBackColor = RgbColor(238,238,238);
    DataAltanateBackColor = RgbColor(255,255,255);
    SumBackColor = RgbColor(242,242,242);
    SelectBackColor = RgbColor(200,250,160);
    SelectHighLight = true;
    SelectFontBold = true;
    SheetFontName = "굴림체";
    SheetFontSize = 9;
    HeadFontColor = RgbColor(255,255,255);
    DataFontColor = RgbColor(102,102,102);
    InLineColor = RgbColor(230,228,234);
    OutLineColor = RgbColor(230,228,234);
    HeadRowHeight = 23;
    DataRowHeight = 22;
    HeadFlat = false;
    EditableColorDiff = true;
    UnEditableColor = RgbColor(242,242,242);
    FocusAfterProcess = false;
    CountPosition = 4;
    CountFontBold = false;
    SearchingImage = "/resource/kr/skin1/images/sheet/grid_search.gif";
    UpLoadImage = "/resource/kr/skin1/images/sheet/grid_upload.gif";
    DownLoadImage = "/resource/kr/skin1/images/sheet/grid_download.gif";
    SavingImage = "/resource/kr/skin1/images/sheet/grid_save.gif";
    WaitImage = "/resource/kr/skin1/images/sheet/grid_wait_d.gif";
    PopupImage = "/resource/kr/skin1/images/sheet/sh_search.gif";
    KeyFieldImage = "/resource/kr/skin1/images/sheet/picon.gif";

  }
*/
  // make header text
  var colCnt = arrC.length;
  var tmpArr = [];
  for ( var n = 0; n < colCnt; n++ )
  {
    tmpArr[tmpArr.length] = arrC[n][0];
  }
  var headerText = tmpArr.join("|");

  if ( location.hostname ) sheet.InitHostInfo(location.hostname, location.port, "");

  sheet.SheetWidth = sheet.parentElement.clientWidth;// 최초 width 세팅
  sheet.MergeSheet = msHeaderOnly;// msNone, msAll, msPrevColumnMerge, msHeaderOnly 머지 설정
  sheet.Editable = true;// false 수정가능여부설정
  sheet.SumFontBold = true;//

  /*
  sheet.InitRowInfo(header0 ? 2 : 1, 1, 10);
  if ( header0 ) sheet.InitHeadRow(0, header0, true);
  sheet.InitHeadRow(header0 ? 1 : 0, headerText, true);
  */
  if ( header0 )
  {
    if ( typeof header0 == "string" )
    {
      sheet.InitRowInfo(2, 1, 10);
      sheet.InitColumnInfo(colCnt, 1, 0, true);// 고정컬럼은 FrozenCols 속성으로 따로 설정
      sheet.InitHeadRow(0, header0, true);
      sheet.InitHeadRow(1, headerText, true);
    }
    else if ( typeof header0 == "object" )
    {
      sheet.InitRowInfo(header0.length + 1, 1, 10);
      sheet.InitColumnInfo(colCnt, 1, 0, true);// 고정컬럼은 FrozenCols 속성으로 따로 설정
      var n = 0;
      for ( n = 0; n < header0.length; n++ )
      {
        sheet.InitHeadRow(n, header0[n], true);
      }
      sheet.InitHeadRow(n, headerText, true);
    }
    else
    {
      alert("Warnig : parameter header0 must be type of string or object(array)...");
    }
  }
  else
  {
    sheet.InitRowInfo(1, 1, 10);
    sheet.InitColumnInfo(colCnt, 1, 0, true);// 고정컬럼은 FrozenCols 속성으로 따로 설정
    sheet.InitHeadRow(0, headerText, true);
  }

  for ( var n = 0; n < colCnt; n++ )
  {
    sheet.InitDataProperty2(0, n, arrC[n][1], arrC[n][2]);
  }

  sheet.RequestTimeOut = 60 * 60;
  sheet.ClipPasteMode = 1;
  sheet.InitComboNoMatchText(true);
  sheet.WordWrap = false;
}

// 공통코드, 객체에서 콤보데이터를 가져온다.
function getComboXS(type, idx_cd, etcParam)
{
  var param = "";
  param += "&S_TYPE="+nvl(type, "");
  //
  param += "&S_IDX_CD="+nvl(idx_cd, "");
  //param += "&S_USE_YN="+nvl(use_yn, "");
  //
  param += "&S_OBJ_TYPE="+nvl(idx_cd, "");
  //param += "&S_YMD="+nvl(use_yn, "");

  param += nvl(etcParam, "");
  return getXSheet("biz.com.ComboDS", "searchCombo01", param);
}

// document 가 ready 되면 IMG, INPUT, BUTTON tag 에 버튼 권한을 적용한다.
function setButtonAuth()
{

  //var startTime = new Date().getTime();

  if ( window.Page == null ) return;

  var esaEmp = "10";
  var esaOrg = "20";
  var esaAll = "30";

  var pageEsaName = decode(Page.EMP_SCH_AUTH, esaEmp, "EMP", esaOrg, "ORG", esaAll, "ALL");

  var canRead = Page.readOk();
  var canWrite = Page.writeOk();
  var canPrint = Page.printOk();
  var imgTags = document.getElementsByTagName("IMG");
  var inputTags = document.getElementsByTagName("INPUT");
  var aTags = document.getElementsByTagName("A");
  var buttonTags = document.getElementsByTagName("BUTTON");
  var spanTags = document.getElementsByTagName("SPAN");
  var divTags = document.getElementsByTagName("DIV");
  $A(imgTags).concat($A(inputTags)).concat($A(aTags)).concat($A(buttonTags)).concat($A(spanTags)).concat($A(divTags)).each(function (e)
  {
    if ( e.BA_TYPE )
    {
      switch ( e.BA_TYPE )
      {
        //case "READ": if ( ! canRead ) e.style.display = "none"; break;
        case "WRITE": if ( ! canWrite ) displayElement(e, false); break;
        case "PRINT": if ( ! canPrint ) displayElement(e, false); break;
      }
    }

    if ( e.BA_TYPE2 && e.BA_TYPE2.indexOf(pageEsaName) < 0)
    {
      displayElement(e, false);
    }

  });

  //alert(new Date().getTime() - startTime);

}

function setBtnAuth()
{
}

// ymd 의 year, month, date 를 inc 만큼 증가시켜 반환
function addYmd(ymd, gbn, inc)
{
  var dt = new Date(Number(ymd.substr(0, 4)), Number(ymd.substr(4, 2))-1, Number(ymd.substr(6, 2)));
  switch ( gbn )
  {
    case "Y": dt.setFullYear(dt.getFullYear() + inc); break;
    case "M": dt.setMonth(dt.getMonth() + inc); break;
    case "D": dt.setDate(dt.getDate() + inc); break;
    // last day of month
    case "LOM":
    {
      dt.setDate(1);
      dt.setMonth(dt.getMonth() + 1);
      dt.setDate(dt.getDate() - 1);
    }
    break;
  }
  return npad(String(dt.getFullYear()), 4) + npad(String(dt.getMonth() + 1), 2) + npad(dt.getDate(), 2);
}

function addYm(ym, inc)
{
  return addYmd(ym.substr(0, 6)+"01", "M", inc).substr(0, 6);
}
// left or right padding
function padLR(str, size, padc, LR)
{
  if ( ! padc ) padc = " ";
  if ( size < str.length ) return str;
  var padcs = "";
  for ( var psize = size - str.length; psize > 0; psize-- )
    padcs += padc;
  return LR == "L" ? padcs + str : str + padcs;
}

// left padding
function lpad(str, size, padc)
{
  return padLR(str, size, padc, "L");
}

// right padding
function rpad(str, size, padc) {
  return padLR(str, size, padc, "R");
}

// number padding
function npad(str, size) {
  return lpad(String(str), size, "0");
}

// 탭을 toggle 한다.
function switchTab(tab, on)
{
  var idx = tab.className.indexOf("_");
  var onoff = tab.className.substr(idx+1);
  var tabSize = tab.className.substr(0, idx);
  if ( on == null )
  {
    tab.className = tabSize+"_"+(onoff == "on" ? "off" : "on");
  }
  else
  {
    tab.className = tabSize+"_"+(on ? "on" : "off");
  }
}

// 지정한 탭을 on 하고 나머지 탭을 off 한다.
function switchTabAll(tab)
{
  var tabs = tab.form[tab.name];
  var idx = null;
  if ( tabs.length || 1 > 1 )
  {
    for ( var n = 0; n < tabs.length; n++ )
    {
      if ( tabs[n] == tab ) idx = n;
      switchTab(tabs[n], tabs[n] == tab);
    }
  }
  else
  {
    idx = 0;
    switchTab(tab, tab == tab);
  }
  return idx;
}

// 스트링 배열(arr)의 각 요소(arr[n])를 시작첨자(s), 마지막첨자(e)를 붙인후 구분자(delim)로 연결한다.
function joinStr(arr, delim, s, e)
{
  delim = nvl(delim, ",");
  s = nvl(s);
  e = nvl(e);
  var arrTemp = new Array();
  for ( var n = 0; n < arr.length; n++ )
  {
    arrTemp[arrTemp.length] = s + arr[n] + e;
  }
  return arrTemp.join(delim);
}

// 시트의 MAX 값 찾기 예) sheet_getMax(sheet1, "GRP2_NO", "CellValue(row, 'GRP1_NO') == "+sheet1.CellValue(row, "GRP1_NO")+"") + 1;
function sheet_getMax(sheet, savename, check_eval_txt)
{
  if ( ! check_eval_txt ) check_eval_txt = "true";
  with ( sheet )
  {
    var max = 0;
    var val;
    for ( var row = HeaderRows, rcnt = 0; rcnt < RowCount; row++, rcnt++ )
    {
      tfCheck = eval(check_eval_txt);

      if ( tfCheck )
      {
        val = Number(CellValue(row, savename));
        if ( val > max ) max = val;
      }
    }
    return max;
  }
}


function sheet_rowData(sheet, row)
{
  var arr = [];
  sheetEachCol(sheet, function(c, svNm, sheet)
  {
    arr.push(sheet.CellValue(row, c));
  });
  return arr;
}

function getObjPropStr(obj)
{
  var s = "";
  for ( var p in obj )
  {
    s += p+"=["+obj[p]+"]\n";
  }
  return s;
}

function UrlEncoding(str)
{
  var rtnStr = "";
  for ( var n = 0; n < str.length; n++ )
  {
    charAt = str.charAt(n);
    encChar = charAt == "?" ? "%3F" :
              charAt == "&" ? "%26" :
              charAt == "=" ? "%3D" :
              charAt == " " ? "+" :
              charAt == "+" ? "%2B" :
              charAt == "%" ? "%25" : charAt;
    rtnStr += encChar;
  }
  return rtnStr;
}

function getSelectedText(sel, defaultText)
{
  sel = $(sel);
  if ( defaultText == null ) defaultText = "";
  return sel.selectedIndex >= 0 ? sel.options[sel.selectedIndex].text : defaultText;
}

function getTermDayCnt(ymdFr, ymdTo)
{
  var dtFr = new Date(Number(ymdFr.substr(0, 4)), Number(ymdFr.substr(4, 2))-1, Number(ymdFr.substr(6, 2)));
  var dtTo = new Date(Number(ymdTo.substr(0, 4)), Number(ymdTo.substr(4, 2))-1, Number(ymdTo.substr(6, 2)));
  return (dtTo.getTime() - dtFr.getTime()) / (1000 * 60 * 60 * 24);
}

function getTermTimeCnt(ymdFr, hmFr, ymdTo, hmTo)
{
  var dtFr = new Date(Number(ymdFr.substr(0, 4)), Number(ymdFr.substr(4, 2))-1, Number(ymdFr.substr(6, 2)), Number(hmFr.substr(0, 2)), Number(hmFr.substr(2, 4)));
  var dtTo = new Date(Number(ymdTo.substr(0, 4)), Number(ymdTo.substr(4, 2))-1, Number(ymdTo.substr(6, 2)), Number(hmTo.substr(0, 2)), Number(hmTo.substr(2, 4)));
  return (dtTo.getTime() - dtFr.getTime()) / (1000 * 60 * 60);
}

// 기간차(rType: Y=년,M=월,D=일,H=시,B=분,S=초)
// Usage: getTermCnt("D","2007","2008"), getTermCnt("B","20070805","20081231132333")
function getTermCnt(rType, ymdhbsFr, ymdhbsTo)
{
  //Declare
  var strYmdhbs = "SBHDMY";
  var arrYmdhbs = new Array(1000,60,60,24,30.417,12);
  var divNum = 1;
  var idxType = strYmdhbs.indexOf(rType.toUpperCase());

  //Check validation
  if( ymdhbsFr > ymdhbsTo || rType.length != 1 ||  idxType < 0 )
  {
    alert("Syntax Error: 시작일, 종료일이 바뀌었거나 형식구분자가 잘못되었습니다.");
    return;
  }

  //나눔수 계산
  for(var i=0; i<=idxType; i++)
  {
    rType.charAt(i);
    divNum = divNum * arrYmdhbs[i];
  }
  //결과
  var dtFr = new Date(Number(ymdhbsFr.substr(0, 4)), Number(ymdhbsFr.substr(4, 2))-1, Number(ymdhbsFr.substr(6, 2)), Number(ymdhbsFr.substr(8, 2)), Number(ymdhbsFr.substr(10, 2)));
  var dtTo = new Date(Number(ymdhbsTo.substr(0, 4)), Number(ymdhbsTo.substr(4, 2))-1, Number(ymdhbsTo.substr(6, 2)), Number(ymdhbsTo.substr(8, 2)), Number(ymdhbsTo.substr(10, 2)));
  return Math.floor((dtTo.getTime() - dtFr.getTime()) / divNum);
}

// substr 을 byte 단위로
function substrb(str, bsidx, bsize) {
	if ( bsidx < 0 ) bsidx = 0;
	var bsidxc = 0;// 비교대상
	var idx = 0;// char index
	while ( true ) {
		if        ( bsidxc  > bsidx ) {   excess = true;  break;
		} else if ( bsidxc == bsidx ) {   excess = false; break;
		}
		if ( idx >= str.length )  return "";
		bsidxc += str.charCodeAt(idx++) > 0x00ff ? 2:1;
	}
	var bsizec = excess ? 1 : 0 ;
	var sidx = idx;
	var remain = false;//
	var size=0;
	while ( true ) {
		if        ( bsizec  > bsize ) { remain = true;  break;
		} else if ( bsizec == bsize ) { break;
		}
		if ( idx >= str.length ) return excess ? " "+ str.substr(sidx) : str.substr(sidx);
		bsizec += str.charCodeAt(idx++) > 0x00ff ? 2:1;
		size++;
	}
	return  (  excess &&   remain) ? " "+ str.substr(sidx, size-1) +" " :
					(  excess && ! remain) ? " "+ str.substr(sidx, size  )      :
					(! excess &&   remain) ?      str.substr(sidx, size-1) +" " :
																				str.substr(sidx, size  );
}





//나중에 제거할 거
/********************************************************************
   (pyk6598@empal.com) 2005-08-04
********************************************************************/
// combodata -> 001|고래#002|오징어#
// combodata 를 code만 또는 name만 array로 가져온다.
function getComboArray(s, idx, rowIdx)
{
  if ( rowIdx == null ) rowIdx = 0;
  var rslt = "";
  var arrcdnm = s.split("#");// 각 [코드|명]을 분리
  var arrtmp = [];

  for ( var n = rowIdx; n < arrcdnm.length; n++ )
  {
    if ( arrcdnm[n] )
    {
      arrtmp[arrtmp.length] = arrcdnm[n].split("@@")[idx];
    }
  }
  return arrtmp;
}
// combodata를 name만 array로 가져온다. sheet 에서 combo 작성시 사용
function getComboText(s, rowIdx)
{
  if ( rowIdx == null ) rowIdx = 0;
  return getComboArray(s, 1, rowIdx).join("|");
}
// combodata를 code만 array로 가져온다. sheet 에서 combo 작성시 사용
function getComboCode(s, rowIdx)
{
  if ( rowIdx == null ) rowIdx = 0;
  return getComboArray(s, 0, rowIdx).join("|");
}
// combodata로 select box 에 append 시킨다.
function makeSelect2(selectObj, text, arr_except)
{
  var arr = text.split("#");

  var cd, nm, cdnm;
  for ( var n = 0; n < arr.length; n++ )
  {
    cdnm = arr[n].split("@@");
    cd = trim(cdnm[0]);
    nm = trim(cdnm[1]);

    if ( arr[n] )
    {
      // 제외 조건
      if ( arr_except != null && array_indexOf(arr_except, cd) >= 0 )
      {
        continue;
      }

      selectObj.options[selectObj.options.length] = new Option(nm, cd);
    }
  }
}

function makeSelect3(sel, grid)
{
  for ( var n = 0; n < grid.RowCount; n++ )
  {
    sel.options[sel.options.length] = new Option(trim(grid_CellValue(grid, n, 1)), trim(grid_CellValue(grid, n, 0)));
  }
}

// write object tag like flash, activex
function writeObjectTag(obj)
{
  var object = document.createElement("object");

  // object attribute setting
  for ( var attr in obj )
  {
    var typeof_obj_attr = typeof obj[attr];
    if ( typeof_obj_attr == "string" || typeof_obj_attr == "number" )
    {
      object[attr] = obj[attr];
    }
  }

  var param;
  for ( var attr in obj.parameters )
  {
    param = document.createElement("param");
    param.name = attr;
    param.value = obj.parameters[attr];
    object.appendChild(param);
  }
//alert(object.outerHTML);
  document.write(object.outerHTML);
  object = null;
}

function submit2(property, parameters)
{
  var form = $E("form", property);
  form["method"] = property["method"] || "post";// default method is post

  var input, value;
  for ( var name in parameters )
  {
    value = parameters[name];
    if ( ["string", "number"].include(typeof value) )
    {
      input = $E("input", {name: name, type: "hidden", value: value});
      form.appendChild(input);
    }
    else if ( typeof value == "array" )
    {
      value.each(function(v)
      {
        input = $E("input", {name: name, type: "hidden", value: v});
        form.appendChild(input);
      });
    }
    else
    {
      input = $E("input", {name: name, type: "hidden", value: value == null ? "" : value});
      form.appendChild(input);
    }
  }
//alert(form.outerHTML);
  document.body.appendChild(form);
  form.submit();
  document.body.removeChild(form);
  form = null;
}


function setCombo(data, comboObj, saveName, option, arrPair, sheetRow)
{
  if ( comboObj == null ) alert("Error: setCombo comboObj("+comboObj+") is null");
  comboObj = typeof comboObj == "string" ? $(comboObj) : comboObj;
  data = [XmlSheet, ScriptSheet].include(data.constructor) ? makeComboTextXS(data) : data;

  if ( comboObj.tagName == "OBJECT" )
  {
    var arrText = [], arrCode = [], arrTemp;
    //□■
    var rowStrings = data.split("■");
    rowStrings.each(function (value, index)
    {
      arrTemp = value.split("□");
      arrText.push(arrTemp[0]);
      arrCode.push(arrTemp[1]);
    });

    var textH = "";
    var codeH = "";

    switch ( option )
    {
      case "A":
      {
        textH = "|전체|";
        codeH = "|%|";
      }
      break;
      case "S":
      {
        textH = "|선택|";
        codeH = "||";
      }
      break;
      case "N":
      {
        textH = "| |";
        codeH = "||";
      }
      break;
      case "U":
      {
        var tmpArrText = [];
        var tmpArrCode = [];
        for ( var n = 0; n < arrPair.length; n++ )
        {
          tmpArrText.push(arrPair[n][0]);
          tmpArrCode.push(arrPair[n][1]);
        }
        textH = arrPair.length == 0 ? "" : tmpArrText.join("|")+"|";
        codeH = arrPair.length == 0 ? "" : tmpArrCode.join("|")+"|";
      }
      break;
    }
    if ( sheetRow == null )
    {
      comboObj.InitDataCombo(0, saveName, textH + arrText.join("|"), codeH + arrCode.join("|"));
    }
    else
    {
      obj.CellComboItem(sheetRow, saveName, textH + arrText.join("|"), codeH + arrCode.join("|"));
    }


  }
  else if ( comboObj.tagName == "SELECT" )
  {
    if      ( option == "A" ) comboObj.options.add(new Option("-전체-", ""));
    if      ( option == "A%" ) comboObj.options.add(new Option("-전체-", "%"));
    else if ( option == "S" ) comboObj.options.add(new Option("-선택-", ""));
    else if ( option == "N" ) comboObj.options.add(new Option("", ""));
    else if ( option == "U" )
    {
      for ( var n = 0; n < arrPair.length; n++ )
        comboObj.options.add(new Option(arrPair[n][0], arrPair[n][1]));
    }

    var arrTemp;
    if ( data )
    {
      var rowStrings = data.split("■");
      rowStrings.each(function (value, index)
      {
        arrTemp = value.split("□");
        comboObj.options.add(new Option(arrTemp[0], arrTemp[1]));
      });
    }
  }
  else
  {
    alert("Wrong...");
  }
}
document.getElementsByTagNames = function()
{
  return $A(arguments).inject([], function(arr, tagName)
  {
    return arr.concat($A(document.getElementsByTagName(tagName)));
  });
}

Progress = {
  count: 0,
  isMade: false,
  layerCover: null,
  layerProgress: null,
  //wels: [],//window elements to be hidden
  start: function()
  {
    if ( ! this.isMade )
    {
      var cssText = "margin: "+document.body.currentStyle.margin+"; position: absolute; top: 0; left: 0; width: 100%; height: 100%; ";//
      //alert(document.body.currentStyle.margin);

      var divCover = document.createElement("div");
      divCover.style.cssText = cssText+"background-color: #EEEEEE; filter: alpha(opacity=10); ";
      divCover.innerHTML = "<table  border=0 cellpadding=0 cellspacing=0 width='100%' height='100%' ><tr><td align='center' valign='middle' ></td></tr></table>";

      var divProgress = document.createElement("div");
      divProgress.style.cssText = cssText;
      divProgress.innerHTML = "<table border=0 cellpadding=0 cellspacing=0 width='100%' height='100%' ><tr><td align='center' valign='middle' ><iframe width=170 height=70 frameborder='0' marginwidth=0 src='/common/jsp/progress.html' SCROLLING=no style='background-color: #EEEEEE; filter: alpha(opacity=60); ' ></iframe></td></tr></table>";

      document.body.appendChild(divCover);
      document.body.appendChild(divProgress);
      this.layerCover = divCover;
      this.layerProgress = divProgress;
      this.isMade = true;
    }
    this.count++;
    if ( this.count == 1 )
    {
      /*
      document.getElementsByTagNames("SELECT", "OBJECT").select(function(e)
      {
        return e.style.display != "none" && e.style.visibility != "hidden";
      }).each(function(e)
      {
        e.style._orgVisibility = e.style.visibility;
        e.style.visibility = "hidden";
        this.wels.push(e);
      }.bind(this));
      */
      Element.show(this.layerCover);
      Element.show(this.layerProgress);
    }
  },
  stop: function()
  {
    this.count--;
    if ( this.count == 0 )
    {
      /*
      this.wels.each(function(e)
      {
        e.style.visibility = e.style._orgVisibility;
      });
      this.wels = [];
      */
      this.layerCover && Element.hide(this.layerCover);
      this.layerProgress && Element.hide(this.layerProgress);
    }
  }
};

ProgressA = {
  count: 0,
  isMade: false,
  layer: null,
  start: function()
  {
    if ( ! this.isMade )
    {
      var o = document.createElement("div");
      var cssText = "margin: "+document.body.currentStyle.margin+"; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: #EEEEEE; filter: alpha(opacity=10); ";//
      o.style.cssText = cssText;
      document.body.appendChild(o);
      this.layer = o;
      this.isMade = true;
    }
    this.count++;
    if ( this.count == 1 ) Element.show(this.layer);
  },
  stop: function()
  {
    this.count--;
    if ( this.count == 0 ) this.layer && Element.hide(this.layer);
  }
};

Alert = {
  isMade: false,
  layerCover: null,
  layerShow: null,
  frame: null,
  alert: function(msg)
  {
    if ( ! this.isMade )
    {
      this.layerCover = $E("div", {style: {cssText:
        "margin: "+document.body.currentStyle.margin+"; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: #EEEEEE; filter: alpha(opacity=50); z-index: 998; "}});
      this.layerShow = $E("div",
        {innerHTML: "<table border=0 cellpadding=0 cellspacing=0 width='100%' height='100%' ><tr><td align='center' valign='middle' ><iframe width=310 height=110 frameborder='0' marginwidth=0 src='/common/jsp/alert.html' SCROLLING=no ></iframe></td></tr></table>", style: {cssText: "margin: "+document.body.currentStyle.margin+"; position: absolute; top: 0; left: 0; width: 100%; height: 100%; ; z-index: 999; "}});
      document.body.appendChild(this.layerCover);
      document.body.appendChild(this.layerShow);
      this.frame = frames[frames.length - 1];

      new Ajax.Request("/common/jsp/alert.html", {
        asynchronous: false,
        onSuccess: function (transport, json)
        {
          this.frame.document.write(transport.responseText);
        }
      });

      this.isMade = true;
    }

    try
    {
      this.frame.document.getElementById("msg").innerText = msg;
    }
    catch(x)
    {
      setTimeout(function (){this.frame.document.getElementById("msg").innerText = msg;}.bind(this), 500);
    }

    Element.show(this.layerCover);
    Element.show(this.layerShow);
  },
  close: function()
  {
    this.layerCover && Element.hide(this.layerCover);
    this.layerShow && Element.hide(this.layerShow);
  }

};

Calendar = {
  iframe: null,
  frameName: "_calendarFrame",
  show: function(input)
  {
    var ymd = getNormalValue(input);
    if ( ! this.iframe )
    {
      var iframe = $E("iframe", {id: this.frameName,
        name: this.frameName,
        frameBorder: 0, src: "/common/jsp/calendar1.jsp?S_SKIN_PATH="+Page.SKIN_PATH+"&S_INPUT_NAME="+input.name+"&S_YMD="+getNormalValue(input),
        style: {
          position: "absolute",
          display: "none",
          width: 200,
          height: 200
        }});
      document.body.appendChild(this.iframe = iframe);
    }

    //alert(topLeft);
    var topLeft = Position.cumulativeOffset(event.srcElement);
    this.iframe.style.left = topLeft[0] + 10;
    this.iframe.style.top = topLeft[1] + 10;

    if ( this.iframe ) this.onShow.bind(this, input, ymd)();
    else setTimeout(this.onShow.bind(this, input, ymd), 500);
  },
  hide: function()
  {
    this.iframe && Element.hide(this.iframe);
  },
  onShow: function(input, ymd)
  {
    frames[this.frameName].calendar && frames[this.frameName].calendar.setInput(input);
    frames[this.frameName].calendar && frames[this.frameName].calendar.setYmd(ymd);
    Element.show(this.iframe);
  }
}

function getCookie( name )
{
  var nameOfCookie = name + "=";
  var x = 0;

  while ( x <= document.cookie.length )
  {
    var y = (x+nameOfCookie.length);
    if ( document.cookie.substring( x, y ) == nameOfCookie )
    {
      if ( (endOfCookie=document.cookie.indexOf( ";", y )) == -1 )
        endOfCookie = document.cookie.length;
      return unescape( document.cookie.substring( y, endOfCookie ) );
    }

    x = document.cookie.indexOf( " ", x ) + 1;

    if ( x == 0 )
      break;
  }
  return "";
}

function setCookie( name, value, expiredays )
{
  var todayDate = new Date();
  todayDate.setDate( todayDate.getDate() + expiredays );
  document.cookie = name + "=" + escape( value ) + "; path=/; expires=" + todayDate.toGMTString() + ";"
}

function downloadFile(target, S_FILE_PATH, S_ORG_FILE_NM)
{
  popopen2({url: "/common/jsp/download.jsp", name: "downloadWindow", param: {
    S_FILE_PATH: S_FILE_PATH, S_ORG_FILE_NM: S_ORG_FILE_NM
  }});
  /*
  var newWin = window.open("/common/jsp/download.jsp", "downloadWindow",
    "top="+((window.screen.height - 100)/2)+", left="+((window.screen.width - 100)/2)+", width=100, height=100, directories=no, location=no, menubar=no, scrollbars=no, status=no, titlebar=no, toolbar=no, resizable=no");
  submit2({action: "/FD", target: "downloadWindow"}, {S_FILE_PATH: S_FILE_PATH, S_ORG_FILE_NM: nvl(S_ORG_FILE_NM)});
  */
  //popopen2({name: "_blank", param: {S_FILE_PATH: S_FILE_PATH, S_ORG_FILE_NM: nvl(S_ORG_FILE_NM)}, url: "/FD"});
}

function ajaxSearchEmp(emp_nm, fn)
{
  ajaxRequestXSProg("biz.sy.Sy181_c01DS", "searchEmp01", {S_EMP_NM: emp_nm}, function(xs)
  {
    var RowCount = xs.RowCount();
    if ( RowCount == 0 )
    {
      alert("검색된 사원이 없습니다.("+emp_nm+")");
      fn({});
    }
    else if ( RowCount > 1 )
    {
      var args;
      var rv = popmodal2(args = {url: "/sy/jsp/sy150_p01.jsp", parameters: {S_SELMODE: "S", S_EMP_NM: emp_nm, X_EMP_SCH_AUTH: Page.EMP_SCH_AUTH}});
      if ( rv == "1" )
      {
        var grid = args.output.grid;
        var RowCount = grid.RowCount;
        var ColCount = grid.ColCount;

        var emp = {};
        for ( var r = 0; r < RowCount; r++ )
        {
          for ( var col = 0; col < ColCount; col++ )
          {
            emp[grid_ColName(grid, col)] = grid_CellValue(grid, r, col);
          }
          fn(emp);
          break;// get only one
        }
      }
      else
      {
        fn({});
      }
    }
    else if ( RowCount == 1 )
    {
      // 검색된 사원이 한명이면
      var EMP_ID = xs.CellValue(0, "EMP_ID");
      ajaxGetEmp(EMP_ID, fn);
    }
  });

}

function ajaxGetEmp(emp_id, fn)
{
  ajaxRequestXSProg("biz.sy.Sy181_c01DS", "getEmp01", {S_EMP_ID: emp_id}, function(xs)
  {
    if ( xs.RowCount() == 0 )
    {
      alert("검색된 사원이 없습니다.("+emp_id+")");
      fn({});
    }
    else
    {
      var emp = {};
      var ColCount = xs.ColCount();
      for ( var col = 0; col < ColCount; col++ )
      {
        emp[xs.ColName(col)] = xs.CellValue(0, col);
      }
      fn(emp);
    }
  });

}

Object.extend2 = function(destination, source) {
  for (var property in source) {
    if ( source[property] == null || source[property].constructor != Object )
      destination[property] = source[property];
    else
      Object.extend2(destination[property], source[property]);
  }
  return destination;
}

$E = function (tagName, props)
{
  var e = document.createElement(tagName);
  Object.extend2(e, props || {});
  return e;
}

function decode()
{
  var x = arguments[0];
  for ( var n = 1, argsLen = arguments.length; n < argsLen; n+=2 )
  {
    if ( x == arguments[n] )
    {
      return arguments[n+1];
    }
    else
    {
      if ( argsLen <= n+2 ) return null;
      else if ( argsLen == n+3 ) return arguments[n+2];
    }
  }
}

function findElement(element, eAttrName, attrName, attrValue, index)
{
  index = index || 0;

  var currIndex = 0;
  while ( element = element[eAttrName] )
  {
    if ( element[attrName] == attrValue )
    {
      if ( currIndex == index )
        return element;
      else
        currIndex++;
    }
  }
  return null;
}

// xsheet 를 이용하여 ImageList 구성한다.
function makeImgXS(sheet, xsheet, data_key)
{
  if ( xsheet == null ) return;
  var arrCd = [];
  var intCnt = -1;

  for ( var row = 0, rcnt = xsheet.RowCount(data_key); row < rcnt; row++ )
  {
    if(xsheet.CellValue(row, 0, data_key) != "")
    {
      intCnt++;

      sheet.ImageList(intCnt) = "/images/icon/"+xsheet.CellValue(row, 0, data_key);
      arrCd[intCnt] = xsheet.CellValue(row, 1, data_key);
    }

  }

  return arrCd;
}

function makeImgApply(sheet, arr, Row, Col, Value)
{
  for ( var row = 0; row < arr.length ; row++ )
  {
    if(arr[row] == Value)
    sheet.CellImage(Row, Col) = row;
  }

}

Math.round2 = function(number, pointCount)
{
  pointCount = pointCount == null ? 0 : pointCount;
  return Math.round(number * Math.pow(10, pointCount)) / Math.pow(10, pointCount);
}

Math.floor2 = function(number, pointCount)
{
  pointCount = pointCount == null ? 0 : pointCount;
  return Math.floor(number * Math.pow(10, pointCount)) / Math.pow(10, pointCount);
}

Math.ceil2 = function(number, pointCount)
{
  pointCount = pointCount == null ? 0 : pointCount;
  return Math.ceil(number * Math.pow(10, pointCount)) / Math.pow(10, pointCount);
}

String.prototype.startsWith = function(p)
{
  var s = this;
  return p == s.substr(0, p.length);
}
// sheet 의 each data row
function sheetEachRow(sheet, f, reverse, startRow, endRow)
{
  reverse = !!reverse;
  var returnObject = {};
  try
  {
    var firstRow = sheet.HeaderRows;
    var lastRow = sheet.HeaderRows + sheet.RowCount - 1;

    if ( reverse )
    {
      var loopStartRow = isNull(startRow) ? lastRow : Math.min(startRow, lastRow);
      var loopEndRow = isNull(endRow) ? firstRow : Math.max(endRow, firstRow);
      for ( var row = loopStartRow; row >= loopEndRow; row-- )
      {
        f(row, sheet, returnObject);
      }
    }
    else
    {
      var loopStartRow = isNull(startRow) ? firstRow : Math.max(startRow, firstRow);
      var loopEndRow = isNull(endRow) ? lastRow : Math.min(endRow, lastRow);
      for ( var row = loopStartRow; row <= loopEndRow; row++)
      {
        f(row, sheet, returnObject);
      }
    }
  }
  catch(e)
  {
    if (e == $break) return returnObject.value;
    else throw e;
  }
}

function isNull(x)
{
  return x == null || x == "";
}
// sheet 의 each col
function sheetEachCol(sheet, f, reverse, startCol)
{
  reverse = !!reverse;
  var returnObject = {};
  try
  {
    if ( reverse )
      for ( var c = nvl(startCol, sheet.LastCol); c >= 0; c-- )
        f(c, sheet.ReadDataProperty(0, c, dpSaveName), sheet, returnObject);
    else
      for ( var c = nvl(startCol, 0), lastC = sheet.LastCol; c <= lastC; c++ )
        f(c, sheet.ReadDataProperty(0, c, dpSaveName), sheet, returnObject);
  }
  catch(e)
  {
    if (e == $break) return returnObject.value;
    else throw e;
  }
}
// 파일 업로드...
function uploadFile(options)
{
  //Progress.start();
  var f = nvl(options.form, document.forms[0]);

  // 임시저장
  var f_encoding = f.encoding;
  var f_method = f.method;
  var f_target = f.target;
  var f_action = f.action;
  // submit
  f.encoding = "multipart/form-data";
  f.method = "post";
  f.target = nvl(options.target, frames[0].name);

  if ( typeof options.OnResult == "function")
  {
    var OnResultFunctionName = "OnResult_"+new Date().getTime();
    window[OnResultFunctionName] = options.OnResult;
    options.OnResult = OnResultFunctionName;
  }

  f.action =
    "/commonAction.do?S_FORWARD=iframeResultXML&S_DSCLASS="+options.S_DSCLASS+"&S_DSMETHOD="+options.S_DSMETHOD+
    "&S_ID="+nvl(options.ID, "")+"&S_FUNCTION="+nvl(options.OnResult, "OnResult")+
    (options.getparam ? "&"+$H(options.getparam).toQueryString() : "")+
    (options.queryString ? "&"+options.queryString : "");



  // submit 시 disabled 된 element 는 안나가므로...다음과 같은 처리가 필요
  var disabledElements = $A(f1.elements).select(function(x) { return x.disabled; });// disabled elements 모으고
  disabledElements.each(function(x) { x.disabled = false; });// enable 해주고

  f.submit();

  disabledElements.each(function(x) { x.disabled = true; });// disable

  // 원복
  f.encoding = f_encoding;
  f.method = f_method;
  f.target = f_target;
  f.action = f_action;

}
// get 파라미터 만들기
function makeParam(obj)
{
  return $H(obj).inject([], function(arr, v)
  {
    arr.push(v.key +"="+ UrlEncoding(v.value));
    return arr;
  }).join("&");
}
// report designer object
function writeRdviewr(option)
{
  var html = "";

  if ( ! window.__teechart )
  {
    html += "<object id=teechart ";
    html += "  classid='clsid:FAB9B41C-87D6-474D-AB7E-F07D78F2422E' ";
    html += "  codebase='/resource/file/teechart7.cab#version=7,0,1,3' ";
    html += "  width=0% height=0% style=margin:0; >";
    html += "</object>";
    window.__teechart = true;
  }

  option = nvl(option, {});
  html += "<object id='"+ nvl(option.id, "rdv1") +"' ";
  html += "  classid='clsid:5A7B56B3-603D-4953-9909-1247D41967F8' ";
  html += "  codebase='/resource/file/rdviewer50u.cab#version=5,0,0,187' ";
  html += "  width='"+nvl(option.width, "100%")+"' height='"+nvl(option.height, "100%")+"' style=margin:0; >";
  html += "</object>";

  document.write(html);

}

RdUtil =
{
  RD_WEBROOT: location.protocol + "//" + location.host,
  RD_DB_PARAM: "/ruseurlmoniker 0 /rcontype [RDAGENT] /rf ["+location.protocol + "//" + location.host+"/RDServer/rdagent.jsp] /rsn [EHR]"
}

function replaceMap(str, map, reg)
{
  var result = str, exec;
  reg = nvl(reg, /\$\{([^}]+)\}/);
  while (exec = reg.exec(result))
  {
    result = result.replace("${"+exec[1]+"}", nvl(map[exec[1]]));
  }
  return result;
}


// combo 의 disabled 에 따라 input text 로 변경...
function convertCombo2Text(combo, enable)
{
  if ( enable )
  {
    Element.show(combo);
    if ( combo.nextSibling && combo.nextSibling.combotextyn == "Y" )
      Element.hide(combo.nextSibling);
  }
  else
  {
    Element.hide(combo);
    if ( combo.nextSibling && combo.nextSibling.combotextyn == "Y" )
    {
      combo.nextSibling.value = getSelectedText(combo);
      Element.show(combo.nextSibling);
    }
    else
      combo.insertAdjacentHTML("afterEnd", "<input type=text value='"+getSelectedText(combo)+"' class=readonly01 readonly size=15 combotextyn=Y >");
  }
}

// sheet 에서 row 검색
function sheetFindRow(sheet, fFind, reverse, startRow)
{
  var findRow = -1;
  sheetEachRow(sheet, function(row, sheet)
  {
    if ( fFind(sheet, row) )
    {
      findRow = row;
      throw $break;
    }
  }, reverse, startRow);
  return findRow;
}

if ( window.Form )
{
  // prototype.js 오버라이드
  Form.serializeElements = function(elements, getHash) {
      var data = elements.inject({}, function(result, element) {
        if ( element.name) {
          var key = element.name, value = $(element).getValue();
          if (value != undefined) {
            if (result[key]) {
              if (result[key].constructor != Array) result[key] = [result[key]];
              result[key].push(value);
            }
            else result[key] = value;
          }
        }
        return result;
      });

      return getHash ? data : Hash.toQueryString(data);
    };
}


function alertHtml(message, mode)
{
  var w = 200;
  var h = 100;

  var dialogWidth = w + "px";
  var dialogHeight = (h+55) + "px";// for ie7.0

  var dialogTop = (window.screen.height - Number(dialogHeight.replace(/\D/g, "")))/2+"px";
  var dialogLeft = (window.screen.width - Number(dialogWidth.replace(/\D/g, "")))/2+"px";

  var args = {message: message, mode: mode||"warn"};
  return window.showModalDialog("/common/jsp/alertHtml.html", args,
    "help: no; status: no; resizable: no; dialogWidth: "+dialogWidth+"; dialogHeight: "+dialogHeight+"; dialogTop: "+dialogTop+"; dialogLeft: "+dialogLeft+"; ");
}
function confirmHtml(message)
{
  return alertHtml(message, "confirm");
}

// 트리 시트 레벨 제어 + - 1 2 3
function printSheetTreeControl(sheetId)
{
  var w = document.write;
  w(" <img src="+Page.SKIN_PATH+"/images/icon/icon_plus.gif onclick='$(\""+sheetId+"\").ShowTreeLevel(-1);' align=absmiddle style=cursor:hand;>");
  w(" <img src="+Page.SKIN_PATH+"/images/icon/icon_minus.gif onclick='$(\""+sheetId+"\").ShowTreeLevel(0, 1);' align=absmiddle style=cursor:hand;>");
  w(" <img src="+Page.SKIN_PATH+"/images/icon/icon_01.gif onclick='$(\""+sheetId+"\").ShowTreeLevel(2, 1);' align=absmiddle style=cursor:hand;>");
  w(" <img src="+Page.SKIN_PATH+"/images/icon/icon_02.gif onclick='$(\""+sheetId+"\").ShowTreeLevel(3, 1);' align=absmiddle style=cursor:hand;>");
  w(" <img src="+Page.SKIN_PATH+"/images/icon/icon_03.gif onclick='$(\""+sheetId+"\").ShowTreeLevel(4, 1);' align=absmiddle style=cursor:hand;>");
}

function sortSheet(sheet)
{
  var rv = popmodal2(args = {url: "/common/jsp/sheetSortConfig.jsp", sheet: $(sheet)});
  if ( rv == "1" )
  {
    $(sheet).ColumnSort(args.Cols, "", args.ColSort, true);
  }
}
// 이미 만들어진 콤보에 권한을 적용한다.
function makeAuthCombo(combo, OPER_CD, CD_TXT, exCode)
{
  switch ( OPER_CD )
  {
    case "ALL":
    {
      //skip
    }
    break;
    case "NOT IN":
    {
      $A(combo.options).reverse().each(function(item)
      {
        // text, value, index
        if ( item.value == "" )
        {
          combo.options.remove(item.index);
        }
        else if ( CD_TXT.indexOf("'"+item.value+"'") >= 0 )
        {
          if ( exCode && exCode == item.value )
          {
          }
          else
          {
            combo.options.remove(item.index);
          }
        }
      });
    }
    break;
    case "IN":
    default:
    {
      $A(combo.options).reverse().each(function(item)
      {
        // text, value, index
        if ( item.value == "" )
        {
          combo.options.remove(item.index);
        }
        else if ( CD_TXT.indexOf("'"+item.value+"'") < 0 )
        {
          if ( exCode && exCode == item.value )
          {
          }
          else
          {
            combo.options.remove(item.index);
          }
        }
      });
    }
    break;
  }

  if ( combo.length == 0 )
  {
    combo.options.add(new Option("----", "----"));
  }
}

function displayElement(element, show)
{
  Element[show?"show":"hide"](element);
}

function sheetAddHiddenDivRow(sheet, saveName)
{
  var prevVal, currVal;
  sheetEachRow(sheet, function(r, x)
  {
    currVal = x.CellValue(r, saveName);
//alert(r);
    if ( prevVal != null && prevVal != currVal )
    {
      x.RowHidden(x.DataInsert(r)) = true;
    }
    prevVal = currVal;
  }, true);
}

function popempcard(c_cd, emp_id, ymd, HTTP_PHOTO_URL)
{
  popmodal2(args = {url: "/common/jsp/rdpop1.jsp",
    param: {S_MRD: "/mrd/emp_card.mrd", S_RDPARAM: "/rv C_CD["+c_cd+"] EMP_ID["+emp_id+"] YMD["+ymd+"] PHOTO_PATH["+(location.protocol + "//" + location.host)+HTTP_PHOTO_URL+"] LOGO_PATH[" + location.protocol + "//" + location.host + "] "}});
}

function showOriginalImage(imgSrc, options)
{
  if ( showOriginalImage.currImage ) document.body.removeChild(showOriginalImage.currImage);
  if ( imgSrc )
  {
    options = options || {};
    var img = document.createElement("img");
    $(img).observe("load", function(evt)
    {
      var applyApperEffect = !! options["applyApperEffect"];
      if ( applyApperEffect ) Element.hide(img);

      //alert($H(evt).inspect());
      var element = evt.srcElement;
      img.id = "img_"+new Date().getTime();
      img.title = "click to close";
      img.style.border = "solid 5 #FFCC00";
      img.style.position = "absolute";
      img.style.zIndex = 999;

      var positionType = options.positionType || "eventPosition";
      if ( positionType == "eventPosition" )
      {
        img.style.top = Math.max(evt.pageY - img.height/2, 0);
        img.style.left = Math.max(evt.pageX - img.width/2, 0);
      }
      else if ( positionType == "center" )
      {
        img.style.top = Math.max((document.body.clientHeight - img.height)/2, 0);
        img.style.left = Math.max((document.body.clientWidth - img.width)/2, 0);
      }

      if ( options.backgroundColor )
      {
        img.style.backgroundColor = options.backgroundColor;
      }


      if ( applyApperEffect )
      {

        if ( ! window.____effects_js )
        {
          var script = document.createElement("script");
          script.src = "/common/js/scriptaculous/effects.js";
          document.body.appendChild(script);
        }

        var startTime = new Date().getTime();
        showOriginalImage.effectInterval = setInterval((function(img)
        {
          if ( window.____effects_js )
          {
            clearInterval(showOriginalImage.effectInterval);
            new Effect.Appear(img);
          }

          if ( new Date().getTime() - startTime > 2000 )
            clearTimeout(showOriginalImage.effectInterval);

        }).bind(null, img), 10);

      }

      if ( options.applyDrag )
      {
        applyDragSimple(img);
      }
      //applyDrag(img, img);
    });
    $(img).observe("click", function(x)
    {
      document.body.removeChild(img);
      showOriginalImage.currImage = null;
    });
    $(img).observe("error", function(x)
    {
      document.body.removeChild(img);
      showOriginalImage.currImage = null;
    });
    document.body.appendChild(img);
    showOriginalImage.currImage = img;
    img.src = imgSrc;
  }
}

var SimpleDragMove = Class.create({
  initialize: function(draggable, handle, options)
  {
    this.draggable = $(draggable);
    this.handle = $(handle || draggable);
    this.options = options||{};

    //Element.setStyle(this.handle, {cursor: "move"});

    this.eventMouseDown = this.beginDrag.bindAsEventListener(this);
    Event.observe(this.handle, "mousedown", this.eventMouseDown);
    var returnFalseFunction = function() { return false; };
    this.handle.ondragstart = returnFalseFunction;
    this.handle.selectstart = returnFalseFunction;
  },

  beginDrag: function(event)
  {
    if ( ! this.init )
    {
      Element.absolutize(this.draggable);
      this.init = true;
    }
    //$("div3").innerText = [event.srcElement.tagName, this.handle.tagName];

    //document.selection.empty();
    document.selection.clear();

    if ( ! this.dragging )
    {

      this.eventClientX = event.clientX;
      this.eventClientY = event.clientY;

      this.handleStartX = Number(this.handle.style.left.replace(/[^0-9]/g,"")) - document.body.scrollLeft;
      this.handleStartY = Number(this.handle.style.top.replace(/[^0-9]/g,"")) - document.body.scrollTop;

      this.applyDocumentEvent(true);

      this.dragging = true;
      //this.handle.innerText = this.dragging;
    }
  },

  dragMove: function(event)
  {
    if ( event.button == 0 )
    {
      this.endDrag();
    }

    //$("div1").innerText = [event.srcElement.tagName, event.type];
    if ( this.dragging )
    {
      var styleLeft = this.handleStartX + event.clientX - this.eventClientX + document.body.scrollLeft;
      var styleTop = this.handleStartY + event.clientY - this.eventClientY + document.body.scrollTop;
      setTimeout(this.setPosition.bind(this, {x: styleLeft, y: styleTop}), this.options.timeoutmillis || 100);
    }
  },

  setPosition: function(xy)
  {
    this.handle.setStyle({left: xy.x, top: xy.y});

    if ( this.options.afterMoveAction )
    {
      this.options.afterMoveAction.bind(this, xy)();
    }
  },

  endDrag: function(event)
  {
    this.applyDocumentEvent(false);

    if ( this.dragging )
    {
      this.dragging = false;
      //this.handle.innerText = this.dragging;
    }
  },

  applyDocumentEvent: function(apply)
  {
    if ( apply )
    {
      if ( !this.eventMouseMove && !this.eventMouseUp )

      this.eventMouseMove = this.dragMove.bindAsEventListener(this);
      this.eventMouseUp = this.endDrag.bindAsEventListener(this);

      Event.observe(document, "mousemove", this.eventMouseMove);
      Event.observe(document, "mouseup", this.eventMouseUp);
      //$("div2").innerText = ++count;

    }
    else
    {
      Event.stopObserving(document, "mousemove", this.eventMouseMove);
      Event.stopObserving(document, "mouseup", this.eventMouseUp);

      this.eventMouseMove = null;
      this.eventMouseUp = null;

      //$("div2").innerText = --count;
    }
  }

});

function applyDragSimple(draggable, handle, options)
{
  new SimpleDragMove(draggable, handle, options);
}

function applyDrag(draggable, handle)
{
  // drag 위한 script 파일 include start

  if ( ! window.____effects_js )
  {
    var script = document.createElement("script");
    script.src = "/common/js/scriptaculous/effects.js";
    document.body.appendChild(script);
  }

  var startTime = new Date().getTime();

  applyDrag.dragdropInterval = setInterval(function()
  {
    if ( ! window.____dragdrop_js )
    {
      clearTimeout(applyDrag.dragdropInterval);
      var script = document.createElement("script");
      script.src = "/common/js/scriptaculous/dragdrop.js";
      document.body.appendChild(script);
    }

    if ( new Date().getTime() - startTime > 2000 )
      clearTimeout(applyDrag.dragdropInterval);
  }, 10);

  applyDrag.draggableInterval = setInterval((function(draggable, handle)
  {
    if ( window.____effects_js && window.____dragdrop_js )
    {
      clearInterval(applyDrag.draggableInterval);
      new Draggable(draggable,{scroll:window,zindex:100,handle:handle
        //,revert:function(element){return true;}
      });
    }

    if ( new Date().getTime() - startTime > 2000 )
      clearTimeout(applyDrag.draggableInterval);

  }).bind(null, draggable, handle), 10);

}

function setElementProperty()
{
  var element = $(arguments[0]);
  var property = element;
  for ( var n = 1, nlen = arguments.length - 2; n < nlen; n++ )
  {
    property = property[arguments[n]];
  }
  property[arguments[arguments.length-2]] = arguments[arguments.length-1];
}

function popSendMail(options)
{
  options = options || {};
  var args;
  popmodal2(args = {url: "/sy/jsp/sy_mail_110_f02.jsp", param: {S_EMP_IDS: options.S_EMP_IDS || ""}});
}

function sheetPopMail(sheet, options)
{
  options = options || {};
  var checkSaveName = options.checkSaveName || "CCHK";
  var empIdSaveName = options.empIdSaveName || "EMP_ID";
  var emp_ids = [];
  sheetEachRow(sheet, function(r, x)
  {
    if ( x.CellValue(r, checkSaveName) == "1" )
    {
      emp_ids.push(x.CellValue(r, empIdSaveName));
    }
  });
  var S_EMP_IDS = emp_ids.join(",");
  popSendMail({S_EMP_IDS: S_EMP_IDS});
}

function greatest()
{
  return $A(arguments).max();
}

function least()
{
  return $A(arguments).min();
}

function getSelectTextValueForSetCombo(sel)
{
  var tmpArray = new Array;
  for ( var n = 0, nlen = sel.options.length; n < nlen; n++ )
  {
    if ( sel.options[n].value )
    {
      tmpArray.push(sel.options[n].text+"□"+sel.options[n].value);
    }
  }
  return tmpArray.join("■");
}

IBSheetUtil = {
  excelDownSelectorIframe: null,
  excelDownSelectorIframeName: null,
  excelDownSelectorSheetId: null,

  showExcelDownSelector: function(options)
  {
    options = options||{};
    var iframe = this.excelDownSelectorIframe;
    var w = 150;
    var h = 100;
    if ( ! iframe )
    {
      var iframeName = "ibsheetexceldownselector_"+new Date().getTime();
      iframe = $E("iframe", {id: iframeName,
        name: iframeName,
        frameBorder: 0,
        src: "/common/jsp/ibsheetExcelDownSelector.jsp?S_SKIN_PATH="+Page.SKIN_PATH,
        style: {
          position: "absolute",
          display: "none",
          width: w,
          height: h
        }});
      Event.observe(iframe, "mouseout", function()
      {
        iframe.removeTimeoutId = setTimeout((function(iframe)
        {
          IBSheetUtil.hideExcelDownSelector();
        }).bind(null, iframe), 500);
      });

      Event.observe(iframe, "mouseover", function()
      {
        if ( iframe.removeTimeoutId )
        {
          clearTimeout(iframe.removeTimeoutId);
          iframe.removeTimeoutId = null;
        }
      });

      document.body.appendChild(iframe);
      frames[frames.length-1].name = iframeName;
      this.excelDownSelectorIframe = iframe;
      this.excelDownSelectorIframeName = iframeName;
    }

    iframe.style.left = Event.pointerX(event)-parseInt(w)+10;
    iframe.style.top = Event.pointerY(event)-10;
    this.excelDownSelectorSheetId = options.sheetId;
    displayElement(iframe, true);
  },
  hideExcelDownSelector: function()
  {
    this.excelDownSelectorIframe && Element.hide(this.excelDownSelectorIframe);
  }
};

FileUpDn =
{
  popUploadFile: function(options)
  {
    options = options || {};
    var rv = popmodal2(args = {url: "/sy/jsp/sy_file_110_p01.jsp", param:
      {S_FILE_NO: options.S_FILE_NO||"",
      S_READONLY_YN: options.S_READONLY_YN||"Y",
      S_ONE_FILE_MGSIZE: options.S_ONE_FILE_MGSIZE||"10",
      S_FILE_LIMIT_CNT: options.S_FILE_LIMIT_CNT||"5"
      }});
    return args.output.formdata.S_FILE_NO[0] || "";
  },
  setLayerFileCnt: function(options)
  {
    options = options || {};
    if ( options.S_FILE_NO )
    {
      ajaxRequestXSProg("biz.sy.SyFileCommonDS", "searchFileCnt", {S_FILE_NO: options.S_FILE_NO}, function(xs)
      {
        $(options.layerId).innerHTML = '<span style="font-weight:bold; color:blue; cursor:hand; " >첨부파일('+xs.EtcData('FILE_CNT')+')</span>';
      });
    }
  },
  // 아래는 파일다운로드...



  fileDownIframe: null,
  fileDownIframeName: "_fileDownloadFrame"+new Date().getTime(),
  showDownFrame: function(options)
  {
    var w = 250;
    var h = 150;
    options = options||{};
    var iframe = this.fileDownIframe;
    var iframeName = this.fileDownIframeName;
    if ( ! iframe )
    {
      iframe = $E("iframe", {
        id: iframeName,
        name: iframeName,
        frameBorder: 0,
        src: "/common/jsp/fileDownList.jsp?S_SKIN_PATH="+Page.SKIN_PATH,
        style: {
          position: "absolute",
          display: "none",
          width: w,
          height: h
        }});

      Event.observe(iframe, "mouseout", function()
      {
        iframe.removeTimeoutId = setTimeout((function(iframe)
        {
          FileUpDn.hideDownFrame();
        }).bind(null, iframe), 500);
      });

      Event.observe(iframe, "mouseover", function()
      {
        if ( iframe.removeTimeoutId )
        {
          clearTimeout(iframe.removeTimeoutId);
          iframe.removeTimeoutId = null;
        }
      });

      document.body.appendChild(this.fileDownIframe = iframe);
    }

    //alert(topLeft);

    if ( options.posLeft != null && options.posTop != null )
    {
//alert([options.posLeft - parseInt(w/2), options.posTop - 20]);
      iframe.style.left = options.posLeft - parseInt(w/2);
      iframe.style.top = options.posTop - 20;
    }
    else if ( event.srcElement )
    {
      var topLeft = Position.cumulativeOffset(event.srcElement);
      iframe.style.left = topLeft[0] - 30;
      iframe.style.top = topLeft[1] - 15;
    }
    else
    {
      iframe.style.left = Event.pointerX(event)-20;
      iframe.style.top = Event.pointerY(event)-15;
    }

    if ( iframe &&
      frames[iframeName] &&
      frames[iframeName].doAction) this.onShowDownFrame.bind(this, options)();
    else setTimeout(this.onShowDownFrame.bind(this, options), 500);
  },
  hideDownFrame: function()
  {
    var iframe = this.fileDownIframe;
    var iframeName = this.fileDownIframeName;
    iframe && Element.hide(iframe);
  },
  onShowDownFrame: function(options)
  {
    var iframe = this.fileDownIframe;
    var iframeName = this.fileDownIframeName;
    options = options||{};
    this.fileNo = options.fileNo||'';
//alert([this.fileNo, frames[this.frameName].doAction]);
    frames[iframeName].doAction && frames[iframeName].doAction("search01");
    Element.show(iframe);
    iframe.focus();
  }

}

// 강제저장용 hidden row 만들기
function sheetInsertHiddenDummyRow(sheet)
{
  var NewRow = sheet.DataInsert(-1);
  var savename, keyfield;
  for ( var n = 0; n <= sheet.LastCol; n++ )
  {
    savename = sheet.ReadDataProperty(0, n, dpSaveName);
    keyfield = sheet.ReadDataProperty(0, n, dpKeyField);
    if ( keyfield )
    {
      sheet.CellValue(NewRow, savename) = "0";
    }
  }
  sheet.RowHidden(NewRow) = true;
  return NewRow;
}

function quoto(str)
{
  return str ? str.replace(/'/g, '\\\'').replace(/"/g, '\\\"') : str;
}

function popImage(src)
{
  var image = new Image();
  image.src = src;
  var w = image.width + 28;
  var h = image.height + 9;
  if (h > 600) { h = 600; }
  //window.open("/common/jsp/popimage.jsp?S_IMG_SRC="+src,'_blank',"width="+w+",height="+h+",resizable=yes,scrollbars=yes,toolbar=no,menubar=no");
  popopen2({url: "/common/jsp/popimage.jsp", name: "ehrpopimage", param: {S_IMG_SRC: src}, features: {width:w,height:h,scrollbars:'yes'}});
}
